from django.db import models
from user.models import Customer
from product.models import Product

# 购物车商品项
class CartItem(models.Model):
    customer = models.ForeignKey(
        Customer,
        on_delete=models.CASCADE,
        related_name='cart_items',
        verbose_name='客户'
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        related_name='cart_items',
        verbose_name='商品'
    )
    quantity = models.IntegerField(
        default=1,
        verbose_name='数量'
    )
    added_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='添加时间'
    )

    class Meta:
        verbose_name = '购物车商品'
        verbose_name_plural = '购物车商品管理'
        unique_together = ('customer', 'product')
        db_table = "cart_cartitem"

    def __str__(self):
        return f'{self.customer.username} - {self.product.name} x {self.quantity}'

    @property
    def total_price(self):
        return self.product.price * self.quantity
